import { defineStore } from "pinia";
import { ref } from "vue";
import { LocalConfig } from "@/types";
import { store } from "./index";

const KEY = "local";

/**
 * 本地配置
 */
export const useLocalStore = defineStore(KEY, () => {
  const config = ref({
    language: getDB().getItem("language") || null,
  } as LocalConfig);

  async function init() {
    const { loadingStore } = store();
    loadingStore.loading("加载个性化配置...");
    if (!config.value.language) {
      // 如果是初次进入网站则设置默认语言
      switch (navigator.language) {
        case "zh-CN":
          setLanguage("cn");
          break;
        case "zh-HK":
          setLanguage("hk");
          break;
        default:
          setLanguage("en");
          break;
      }
    }
  }

  function setLanguage(language: string) {
    config.value.language = language;
    localStorage.setItem("language", language);
  }

  function getLanguage(): string {
    return config.value.language;
  }

  function getDB() {
    return localStorage;
  }

  return {
    init,
    setLanguage,
    getLanguage,
  };
});
